package org.watchrecords.annotations;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.mallardsoft.tuple.Pair;
import com.mallardsoft.tuple.Tuple;

public class UniqueNamedValidator implements ConstraintValidator<UniqueNamed, Pair<Integer, String>> {
    @Inject private static Provider<EntityManager> emProvider;
    private String namedQuery;
    
    @Override
    public void initialize(UniqueNamed annotation) {
        namedQuery = annotation.namedQuery();
    }

    @Override
    public boolean isValid(Pair<Integer, String> pair, ConstraintValidatorContext context) {
        Query query = emProvider.get().createNamedQuery(namedQuery);
        query.setParameter("id", Tuple.get1(pair));
        query.setParameter("name", Tuple.get2(pair));
        
        return (Long) query.getSingleResult() == 0;
    }
}
